/*
 * Date: 2021/4/8
 * Author: January
 * Description: 日志消息打印接口实现文件，依赖于printf的实现
 */
#include <libecc/lib_ecc_config.h>

#ifdef WITH_LOG
#include <libecc/words/words.h>
#ifndef IMP_PRINTF
#define IMP_PRINTF printf 
#endif

#define PREVIEW_MAX 512
#define LINE_LEN 24

int byte2hex(uint8_t byte, char* out) {
    uint8_t high,low;
    const char* hexnums = "0123456789abcdef";
    high = (byte & 0xf0) >> 4;
    low = byte & 0x0f;
    out[0] = hexnums[high];
    out[1] = hexnums[low];
    return 2;
}

void printBytes(const void* bytes, int len, const char* prompt) {
    int i = 0;
    int j = 0;
    int row_size;
    char c;
    uint8_t* p = (uint8_t*)bytes;
    static char line_buff[128];
    char* lp;

    lp = line_buff;

    if (prompt != NULL) {
        IMP_PRINTF("%s:\n",prompt);
    }
    len = (len > PREVIEW_MAX)? PREVIEW_MAX : len;

    for (i=0; i<len; i+=j) {
        row_size = (LINE_LEN <= len - i)? LINE_LEN : len - i;
        lp = line_buff;
        for (j=0; j<row_size; j++) {
            lp += byte2hex(*(p+i+j), lp);
            lp[0] = ' '; lp++;
            if (j % 2 != 0) {
                lp[0] = ' '; lp++;
            }
        }
        // use space to fill the row
        for(; j < LINE_LEN; j++) {
            lp[0] = ' '; lp[1] = ' '; lp[2] = ' '; lp += 3;
            if (j % 2 != 0) {
                lp[0] = ' '; lp++;
            }
        }

        for (j=0; j<row_size; j++) {
            c = *(char*)(p + i + j);
            if (c <= ' ' || c > '~') {
                c = '.';
            }
            *lp = c;
            lp++;
        }

        for (;j < LINE_LEN; j++) {
            *lp = ' ';
            lp++;
        }
        *lp = 0;
        IMP_PRINTF("%s\n", line_buff);
    }
}
#endif